package com.legal.aid.app.controller;

import com.legal.aid.app.domain.vo.CommonUserVo;
import com.legal.aid.app.service.IAppUserService;
import com.legal.aid.app.utils.OssService;
import com.legal.aid.common.constant.Constants;
import com.legal.aid.common.core.domain.AjaxResult;
import com.legal.aid.common.core.domain.model.AppLoginUser;
import com.legal.aid.common.core.domain.model.LoginBody;
import com.legal.aid.common.core.domain.model.RegisterBody;
import com.legal.aid.common.utils.SecurityUtils;
import com.legal.aid.common.utils.StringUtils;
import com.legal.aid.framework.web.service.SysLoginService;
import com.legal.aid.framework.web.service.SysRegisterService;
import com.legal.aid.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.legal.aid.common.core.domain.AjaxResult.error;
import static com.legal.aid.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/app")
public class AppUserController {
    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private OssService ossService;

    // 这里如果已经在其他地方配置好全局异常处理，可不用重复捕获异常
    // 若没有全局异常处理，可参考如下方式捕获异常并返回友好提示
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = success();

        // 调用SysLoginService中的login方法进行登录验证
        String token = sysLoginService.loginApp(loginBody.getUsername(), loginBody.getPassword(),
                loginBody.getCode(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);

        return ajax;
    }

    @GetMapping("/hi")
    public AjaxResult login() {
        AjaxResult ajax = success();

        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUserVo userVo = appUserService.getByUserId(appLoginUser.getCommonUser().getId().toString());

        // 打印userVo对象，重点关注isLawyer字段
        System.out.println("getInfo返回的userVo: " + userVo);

        return success(userVo); // 此时 data 字段为 userVo
    }

    /**
     * 获取用户详情
     * 
     * @return
     */
    @GetMapping("/getUserDetails/{userId}")
    public AjaxResult getUserDetail(@PathVariable String userId) {
        CommonUserVo userVo = appUserService.getByUserId(userId);
        return success(userVo); // 此时 data 字段为 userVo
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user) {
        if (!("true".equals(configService.selectConfigByKey("app.account.registerUser")))) {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.registerAppUser(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    /**
     * 上传并更新用户头像
     */
    @PostMapping("/avatar/upload")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 上传文件到OSS
            String avatarUrl = ossService.uploadAvatar(file);
            // 更新用户头像
            AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
            if (appUserService.updateUserAvatar(appLoginUser.getCommonUser().getId(), avatarUrl)) {
                Map<String, String> data = new HashMap<>();
                data.put("avatarUrl", avatarUrl);
                return success(data);
            }
            return error("更新头像失败");
        } catch (IOException e) {
            return error("上传头像失败：" + e.getMessage());
        }
    }
}